#include"Connector.h"

Connector::Connector(Selector* pSelector,IMessageChannelFactory* pFactory)
{
	m_pSelector = pSelector;
	m_pFactory = pFactory;
}

bool Connector::Connect(const char* ip,unsigned int port,IMessageSystem::CallBack::OnConnectSuccess s,IMessageSystem::CallBack::OnConnectFail f,void* pTag)
{	
	m_pTag = pTag;
	m_Success = s;
	m_Fail = f;
	m_ip = ip;
	m_port = port;
	sockaddr_in saddr;
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(port);
	saddr.sin_addr.s_addr = inet_addr(ip);
	
	m_socket = ::socket(AF_INET,SOCK_STREAM,0);
	Platform::SetNonBlock(m_socket);
        int ret = ::connect(m_socket,(sockaddr*)&saddr,sizeof(sockaddr_in));

	if ( 0 == ret )
	{
		OnResult(true);
		return true;
	}
	else
	{
		int err = GetLastError();
		if ( err != WSAEINPROGRESS && err != WSAEWOULDBLOCK )
		{
			OnResult(false);
			return true;
		}
		else
		{
			m_pSelector->Register(m_socket);
			return false;
		}
	}		
}

bool Connector::Poll()
{
	if ( m_pSelector->CanWrite(m_socket) ) 
	{
		OnResult(true);
		return true;
	}

	if ( m_pSelector->IsException(m_socket) )
	{
		OnResult(false);
		return true;
	}

	return false;
}

void Connector::OnResult(bool bSuccess)
{
	if( bSuccess )
	{
		IMessageChannel* pMC = m_pFactory->Create(m_socket);
		m_Success(pMC,m_pTag);
	}
	else
	{
		Platform::Close(m_socket);
		m_pSelector->UnRegister(m_socket);
		m_Fail(m_pTag);
	}
}
